package cn.xlbweb.cli.common;

import cn.xlbweb.util.res.ResponseServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author: bobi
 * @date: 2019-02-04 00:55
 * @description:
 */
@RestControllerAdvice
@Slf4j
public class CommonException {

    /**
     * 使用@Valid验证请求实体校验失败后抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public ResponseServer bindException(BindException e) {
        log.error("参数绑定异常", e);
        return ResponseServer.error(e.getFieldError().getDefaultMessage());
    }

    /**
     * 使用@RequestParam上的validate失败后抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResponseServer constraintViolationException(ConstraintViolationException e) {
        log.error("参数格式异常", e);
        return ResponseServer.error(e.getMessage());
    }

    /**
     * 使用@RequestBody上的validate失败后抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseServer methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常", e);
        return ResponseServer.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseServer exception(Exception e) {
        log.error("发生异常", e);
        return ResponseServer.error(e.getMessage());
    }
}
